package com.tidy.seed.configuration;

import com.tidy.seed.interceptor.ApiLogInterceptor;
import com.tidy.seed.interceptor.LoginInterceptor;
import com.tidy.seed.interceptor.PermissionInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.io.File;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Resource
    private LoginInterceptor loginInterceptor;

    @Resource
    private PermissionInterceptor permissionInterceptor;

    @Resource
    private ApiLogInterceptor apiLogInterceptor;
    @Resource
    private FileUploadConfig fileUploadConfig; // 注入上传配置，获取上传路径

    @Value("${custom.file-upload-prefix}")
    private String fileUploadPrefix;

    private String apiDomain;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/doc.html",
                        "/webjars/**",
                        "/v3/api-docs/**",
                        "/swagger-resources/**",
                        "/swagger-ui/**",
                        "/error"// 排除错误处理路径
                );
        registry.addInterceptor(permissionInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/doc.html",
                        "/webjars/**",
                        "/v3/api-docs/**",
                        "/swagger-resources/**",
                        "/swagger-ui/**",
                        "/error"// 排除错误处理路径
                );
        registry.addInterceptor(apiLogInterceptor)
                .addPathPatterns("/**") // 拦截所有请求
                .excludePathPatterns(
                        "/doc.html",
                        "/webjars/**",
                        "/v3/api-docs/**",
                        "/swagger-resources/**",
                        "/swagger-ui/**",
                        "/error"// 排除错误处理路径
                ); // 排除非业务接口
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String uploadPath = fileUploadConfig.getRootPath();
        if (!uploadPath.endsWith(File.separator)) {
            uploadPath += File.separator;
        }
        // 映射 /upload/** URL 到磁盘上的上传目录
        registry.addResourceHandler(fileUploadPrefix + "/**")
                .addResourceLocations("file:" + uploadPath);
    }
}
